package com.smart.home.controller.User;

import com.smart.home.constant.UsersConstant;
import com.smart.home.dto.User.UserLoginDto;
import com.smart.home.dto.User.UserRegisterDto;
import com.smart.home.entity.Users;
import com.smart.home.properties.JwtProperties;
import com.smart.home.service.UserService;
import com.smart.home.result.Result;
import com.smart.home.utils.DeviceFingerprintUtil;
import com.smart.home.utils.JwtUtil;
import com.smart.home.vo.UserLoginVo;
import com.smart.home.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 用户管理模板
 */

@RestController
@RequestMapping("/user")
@Slf4j
@Api(tags = "用户管理模板")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 用户注册,返回ID,要实现自动插入需要相关Apo 先配置apo
     * @param userRegisterDto
     * @return
     */
    @ApiOperation( "用户注册")
    @PostMapping( "/register")
    public  Result<Integer>  register(@RequestBody UserRegisterDto userRegisterDto) {
        log.info("用户注册,参数:{}",userRegisterDto);
        Integer id = userService.register(userRegisterDto);
        return Result.success(id);
    }

    /**
     *  用户登入 返回 userLoginVo
     * @param userLoginDto
     * @return Result<UserLoginVo>
     */
     @ApiOperation( "用户登入")
     @PostMapping( "/login")
      public  Result<UserLoginVo>  login(@RequestBody UserLoginDto userLoginDto , HttpServletRequest request) {
        log.info("用户登入");
        Users users = userService.login(userLoginDto);


        //获取token，并存储设备指纹和登入信息（详细请看service层）
         Map<String,Object> claims = new HashMap<>();
         claims.put("id",users.getId());
         String token = JwtUtil.createJWT(
                 jwtProperties.getAdminSecretKey(),
                 jwtProperties.getAdminTtl(),
                 claims
         );

        String deviceFingerprint = DeviceFingerprintUtil.getFingerprint(request);
        log.info("设备指纹：{}",deviceFingerprint);
        String tokenKey = UsersConstant.USER_REDIS_TOKEN_KEY + users.getId() + ":" + deviceFingerprint;
        redisTemplate.opsForValue().set(tokenKey,token,jwtProperties.getAdminTtl(), TimeUnit.SECONDS);



         UserLoginVo userLoginVo = UserLoginVo.builder()
                .userName(users.getUsername())
                .id(users.getId())
                .token(token)
                .build();

        return Result.success(userLoginVo);
    }

    /**
     * 用户登出
     * @return
     */
    @ApiOperation( "用户登出")
    @PostMapping("/logout")
    public Result logout(HttpServletRequest request){
        log.info("用户登出");
        log.info("{}",request);
        userService.logout(request);
        return Result.success();
    }

    /**
     * 修改密码,在修改密码的地方也要验证次数
     * @param oldPassword
     * @param newPassword
     * @return
     */
    @ApiOperation( "修改密码")
    @PutMapping("/password")
    public Result UpdatePassword(String oldPassword, String newPassword){
        log.info("修改密码：原密码：{}，修改密码:{}",oldPassword,newPassword);
        userService.UpdatePassword(oldPassword,newPassword);
        return Result.success();
    }

    /**
     * 返回当前用户信息
     * @return
     */
    @ApiOperation( "返回当前用户信息")
    @GetMapping("/info/{id}")
    public Result<UserVO> queryUserInfo(@PathVariable Long id){
        log.info("返回当前用户信息");
        UserVO usersVo= userService.queryUserInfo(id);
        return Result.success(usersVo);
    }

}
